package com.flick.user.services;

import com.flick.common.Result;
import com.flick.po.User;
import com.flick.user.dao.UserDao;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserService {

    @Autowired
    UserDao dao;

    public List<User> list(){
        return dao.findAll();
    }

    public Page<User> page(Integer page, Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return dao.findAll(pageable);
    }

//    public List<User> save(List<User> list){
//
//        return dao.saveAll(list);
//    }
    @SneakyThrows
    @HystrixCommand(fallbackMethod = "saveFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间范围内
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60") //失败率打到多少后断路
    })
    public Result save(Integer sec){
        Thread.sleep(sec * 1000);
        return new Result("运行时间为:" + (sec * 1000) + "秒");
    }

//    public Result saveFallback(Integer sec){
//        log.error("服务降级启动");
//        return new Result("500","服务调用超时,请稍后再试");
//    }
}
